const MYSQL = require("../../sql/mysql");
const MYSQLConfig = require("../../sql/database");
const dictionaryListSqlName = MYSQLConfig.datasheetName.dictionary_list;
const dictionaryValuesSqlName = MYSQLConfig.datasheetName.dictionary_values;
// 字典->词条->词条内容
/**
 * 字典树
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
async function DictionaryTreeList() {}
/**
 * 字典列表
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
async function DictionaryList() {
  try {
    let query = `
        SELECT *,(SELECT COUNT(*) FROM ${dictionaryValuesSqlName} WHERE dic_id = ${dictionaryListSqlName}.id ) as count FROM ${dictionaryListSqlName} 
        `;
    const conn = await MYSQL.promise().getConnection();
    let result = await conn.query(query);
    let list = result[0];

    // 释放Mysql池
    await conn.release();
    return {
      code: 0,
      msg: "获取成功",
      data: {
        page: null,
        list,
      },
    };
  } catch (error) {
    throw { code: 500, msg: "获取失败" };
  }
}
/**
 * 新增字典
 * @param {object} params 验证码id
 * @param {string} params.id 作废的验证码id
 * @param {string} params.state 作废后的验证码状态
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
async function AddDictionary(Request) {
  try {
    let Body = Request.body;

    let { name, title, comment } = Body;

    // 验证参数
    if (!name) {
      throw { code: 500, msg: "添加失败，name不能为空" };
    }
    if (!title) {
      throw { code: 500, msg: "添加失败，title不能为空" };
    }

    // 判断是否存在相同的字典
    let MysqlQuery = `
            SELECT * from ${dictionaryListSqlName} WHERE name = '${name}' AND state = 1
        `;
    // 获取MYSQL 池连接
    const Conline = await MYSQL.promise().getConnection();
    // 开始查询是否存在相同字典
    let ifExistMysql = await Conline.query(MysqlQuery);
    let ifExist = ifExistMysql[0].length > 0;
    if (ifExist) {
      throw { code: 500, msg: "添加失败，字典已存在" };
    }

    let create_date = Request.$requestTime;

    let insertResult = await Conline.query(
      `INSERT INTO ${dictionaryListSqlName} SET ?`,
      {
        title,
        comment,
        name,
        create_date,
      }
    );

    // 查询完毕，释放池连接回池
    await Conline.release();

    let affectedRows = insertResult[0].affectedRows;

    if (affectedRows) {
      return {
        code: 0,
        msg: "添加成功",
      };
    } else {
      throw {
        code: 500,
        msg: "添加失败",
      };
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}
/**
 * 删除字典
 * @param {object} params 验证码id
 * @param {string} params.id 作废的验证码id
 * @param {string} params.state 作废后的验证码状态
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
async function Deletedictionary(Request) {
  try {
    let Body = Request.body;
    let { id } = Body;
    if (!id) {
      throw {
        code: 500,
        msg: "删除失败，id不能为空",
      };
    }
    // 获取MYSQL 池连接
    const Conline = await MYSQL.promise().getConnection();
    let query = `
           DELETE FROM ${dictionaryListSqlName} WHERE id = '${id}'
        `;
    let DeleteResult = await Conline.query(query);

    let affectedRows = DeleteResult[0].affectedRows;

    // 查询完毕，释放池连接回池
    await Conline.release();

    if (affectedRows) {
      return {
        code: 0,
        msg: "删除成功",
      };
    } else {
      throw {
        code: 500,
        msg: "删除失败",
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 更新字典信息
 * @param {object} params 验证码id
 * @param {string} params.id 作废的验证码id
 * @param {string} params.state 作废后的验证码状态
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
async function UpdateDictionary() {}
/**
 * 字典内容列表
 * @param {object} params 验证码id
 * @param {string} params.id 作废的验证码id
 * @param {string} params.state 作废后的验证码状态
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
async function DictionaryValueList(Request) {
  try {
    let Query = Request.query;
    let { id, page, limit } = Query;
    if (!id) {
      throw { code: 500, msg: "操作失败,id不能为空" };
    }
    limit = limit < 10 ? (limit = 1) : limit;
    page = page < 1 ? (page = 1) : page;
    let sqlName = "dictionary_values";

    // 获取MYSQL 池连接
    const Conline = await MYSQL.promise().getConnection();

    let result = await Conline.query(`
      SELECT * FROM ${sqlName} WHERE dic_id = ${id}
      LIMIT  ${limit} OFFSET ${(page - 1) * limit};
    `);
    // 获取数据总数 =====
    let totalResult = await Conline.query(
      `
          SELECT Count(*) AS total FROM ${sqlName} WHERE dic_id = ${id}
      `
    );
    // 取出数据总数
    let total = totalResult[0][0].total;
    // 根据数据总数计算总页数
    let pages = Math.ceil(total / limit);
    // 查询完毕，释放池连接回池
    await Conline.release();
    let list = result[0];
    return {
      code: 0,
      msg: "获取成功",
      data: {
        total,
        page,
        pages,
        limit,
        list,
      },
    };
  } catch (error) {
    console.log(error)
    throw error;
  }
}
/**
 * 清空字典内容
 * @param {object} params 验证码id
 * @param {string} params.id 作废的验证码id
 * @param {string} params.state 作废后的验证码状态
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
async function EmptyDictionaryValue(Request) {
  try {
    // 获取MYSQL 池连接
    const Conline = await MYSQL.promise().getConnection();
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "清空成功",
    };
  } catch (error) {
    throw error;
  }
}

module.exports = {
  EmptyDictionaryValue,
  AddDictionary,
  DictionaryList,
  DictionaryValueList,
};
